﻿using GetSmartIDEList.Lib.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace GetSmartIDEList.Lib.Common
{
    public abstract class SQLXMLHelper
    {

        /// <summary>
        /// 操作sql集合
        /// </summary>
        public static DataInf data => (DataInf)Deserialize(typeof(DataInf), "DataInf.xml");

        /// <summary>
        /// 用于缓存xml的内容，减少读写次数。
        /// </summary>
        private static Hashtable ConfigHashtable = new Hashtable();

        /// <summary>
        /// 获取变量的值
        /// </summary>
        /// <param name="KeyName"></param>
        /// <returns></returns>
        private static object GetValue(string KeyName)
        {
            return ConfigHashtable.ContainsKey(KeyName) ? ConfigHashtable[KeyName] : null;
        }

        /// <summary> 
        /// XML反序列化成对象
        /// </summary> 
        /// <param name="type">类型</param> 
        /// <param name="XmlFileName">XML文件名称</param> 
        /// <returns></returns> 
        public static object Deserialize(Type type, string XmlFileName)
        {
            try
            {
                object obj = GetValue(XmlFileName);
                if (obj == null)
                {
                    string pathTo = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    string directory = System.IO.Path.GetDirectoryName(pathTo);

                    string XmlFilePath = directory + "\\SQLXml\\" + XmlFileName;
                    using (XmlReader reader = XmlReader.Create(XmlFilePath))
                    {
                        XmlSerializer xmldes = new XmlSerializer(type);
                        obj = xmldes.Deserialize(reader);
                        if (ConfigHashtable.ContainsKey(XmlFileName))
                        {
                            ConfigHashtable[XmlFileName] = obj;
                        }
                        else
                        {
                            ConfigHashtable.Add(XmlFileName, obj);
                        }
                    }
                }
                return obj;
            }
            catch (Exception)
            {
                return null;

            }
        }
    }
}
